import AttributeUtil from '@/AttributeUtil';
import RandomUtil from '@/RandomUtil';

export default class RandomCommon {
    /**
     * 根据权重随机一个整数，数值越大，机率越小
     * @param min 最小值
     * @param max 最大值
     * @returns number
     */
    static randomIntByWeight(min: number, max: number, rate: number = 3) {
        // 计算每个值的权重
        let table: { v?: number; w?: number }[] = [];
        let mid = max - min + 1;
        for (let i = 0; i < mid; i++) {
            table.push({
                v: i + min,
                // w: Math.pow(mid - i, rate),
                w: mid - i,
            });
        }

        // 计算总权重
        let sum = 0;
        for (let item of table) {
            sum += item.w;
        }
        // 从总权重中随机
        let r = RandomUtil.nextReal(0, sum);
        let v = min;
        for (let item of table) {
            // 根据权重判断
            r -= item.w;
            if (r <= 0) {
                v = item.v;
                break;
            }
        }
        return v;
    }
    static randomRealByWeight(min: number, max: number) {
        // 0.35,0.25,0.2,0.15,0.5
        // 先把区间分成多个不等份
        // 0,0.1,0.15,0.2,0.25,0.3
        let grid = [0, 0.1, 0.25, 0.45, 0.75, 1];
        let table: { v?: number; i?: number; w?: number }[] = [];
        let mid = max - min;
        for (let i = 0; i < grid.length; i++) {
            table.push({
                v: min + grid[i] * mid,
                i: i,
            });
        }

        // 分配权重
        let max2 = table[table.length - 1].i;
        let min2 = table[0].i;
        let mid2 = max2 - min2;

        for (let i = 0; i < mid2; i++) {
            // table[i].w = Math.pow(mid2 - i, 3);
            table[i].w = mid2 - i;
        }
        // 求总权重
        let sum = 0;
        for (let i = 0; i < table.length - 1; i++) {
            sum += table[i].w;
        }
        // 随机区间所在索引
        let r = RandomUtil.nextReal(0, sum);
        let index = 0;
        for (let i = 0; i < table.length - 1; i++) {
            r -= table[i].w;
            if (r <= 0) {
                index = table[i].i;
                break;
            }
        }

        // 从区间中随机数据
        let max3 = table[index + 1].v;
        let min3 = table[index].v;

        let res = RandomUtil.nextReal(min3, max3);
        return res;
    }
    static setRandomSeed() {
        let seed = GetRandomInt(-2147483648, 2147483647);
        SetRandomSeed(seed);
    }
    static getSkillRate(base: number, caster: unit, abilityId: string | number) {
        let attr = AttributeUtil.getUnitAttribute(caster);
        if (attr != null) {
            if (typeof abilityId == 'number') {
                abilityId = id2string(abilityId);
            }
            base += (attr?.[abilityId + '_effect_rate'] as number) ?? 0;
        }
        return base;
    }
}
